package net.example.hasor.auth;
import net.hasor.dataway.DatawayApi;
import net.hasor.dataway.authorization.PermissionType;
import net.hasor.dataway.spi.AuthorizationChainSpi;
import net.hasor.web.invoker.HttpParameters;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.inject.Singleton;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;

import static net.hasor.dataway.authorization.PermissionGroup.Group_Execute;
import static net.hasor.dataway.authorization.PermissionGroup.Group_ReadOnly;

@Singleton
public class AuthAuthorizationChainSpi extends AbstractAuth implements AuthorizationChainSpi {
    public AuthAuthorizationChainSpi() throws NoSuchAlgorithmException {
        super();
    }

    @Override
    public boolean doCheck(PermissionType permission, DatawayApi apiInfo, boolean defaultCheck) {
        // 方法改造：根据token判断用户角色是否能够调用接口
//        HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
////        String cookieValue = httpRequest.getHeader("DW_TOKEN");
//        Cookie[] cookies = httpRequest.getCookies();
//        boolean checkToken = false;
//        String cookieValue = "";
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equalsIgnoreCase(COOKIE_NAME)) {
//                    cookieValue = cookie.getValue();
//                }
//            }
//        }
//        if (cookieValue != null && cookieValue.equalsIgnoreCase(USER_TOKENS)) {
//            checkToken = true;
//        }
//        if (cookieValue != null && cookieValue.equalsIgnoreCase(ADMIN_TOKENS)) {
//            checkToken = true;
//        }
//        if(!checkToken) {
//            return false;
//        }

        Object attribute = HttpParameters.localInvoker().getHttpRequest().getAttribute(ROLE_ATTR_NAME);
        if (ROLE_ADMIN.equals(attribute)) {
            return true;
        }
        return Group_ReadOnly.testPermission(permission) || Group_Execute.testPermission(permission);
    }
}
